package com.peg.rules;

import com.peg.dataobjects.Context;

/**
 * @author sad
 */
public class StringRule extends Rule {

    private boolean _ignoreCase;
    private char[] _match;

    public StringRule(String match, boolean ignoreCase) {
        _match = ignoreCase ? match.toUpperCase().toCharArray() : match.toCharArray();

        _ignoreCase = ignoreCase;
    }

    @Override
    public boolean execute(Context context) {
        if (_ignoreCase) {
            for (char c1 : _match) {
                char c2 = context.getNextChar();
                c2 = Character.toUpperCase(c2);
                if (c1 != c2) {
                    return false;
                }
            }
        } else {
            for (char c1 : _match) {
                char c2 = context.getNextChar();
                if (c1 != c2) {
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public String toString() {
        if (_ignoreCase) {
            return "String rule match ignore case[" + new String(_match) + "]";
        } else {
            return "String rule match[" + new String(_match) + "]";
        }
    }
}
